/*
 * Gallery
 *
 */

;(function(win){
	var Gallery = win.Gallery = function(options){
		options || (options = {});
		this.pageQuantity = options.pageQuantity || 8;
		this.loadQuantity = options.loadQuantity || 8;
		this.imageSufix = options.imageSufix || "_s";
		var element = options.element || '.gallery';
		if(typeOf(element) === 'string'){
			element = document.getElement(element);
		}
		this.$el = element;
		this.navPre = document.getElement('.nav-btn[role=pre]');
		this.navNext = document.getElement('.nav-btn[role=next]');
		this.pager = new Pager('.pager');
		this.photos = [];
		this.rawData = [];
		this.operatingData = [];
		this.processing = false;
		this.setup();
	};
	Gallery.prototype.transition = function(isNext, currentPhotos, nextPhotos){
		var ele = this.$el;
		ele.empty();
		var floatValue = isNext ? 'left' : 'right';
		var htmlString = '<div class="room"><ul class="pre" style="float:' + floatValue + '">';
		currentPhotos.forEach(function(photo){
			var selected = photo.isSelected ? 'selected' : '';
			htmlString += '<li photo_id="' + photo.photo_id + '" class="gallery-photo ' + selected + '"><img src="' + photo.filename + '"></li>';
		});
		floatValue = isNext ? 'right' : 'left';
		htmlString += '</ul><ul class="current" style="float:' + floatValue + '">';
		nextPhotos.forEach(function(photo){
			var selected = photo.isSelected ? 'selected' : '';
			htmlString += '<li photo_id="' + photo.photo_id + '" class="gallery-photo ' + selected + '"><img src="' + photo.filename + '"></li>';
		});
		htmlString += '</ul></div>';
		ele.appendHTML(htmlString);
		var room = ele.getElement('.room');
		// update time for the info board
		var timeString = nextPhotos[0]['timestamp'];
		var d = new Date(Number.from(timeString));
		timeString = d.toLocaleDateString() + " " + d.toLocaleTimeString();

		var handleComplete = function(){
			room.setStyle('left', '0px');
			room.getElement('.pre').destroy();
			room.getElement('.current').setStyle('float', 'none');
			$('updateTime').set('text', timeString);
		};
		if(!isNext){
			room.setStyle('left', '-1160px');
			TweenLite.to(room, .6, {left:'0', onComplete: handleComplete});
		}else{
			TweenLite.to(room, .6, {left: '-1160', onComplete: handleComplete});
		}
	}
	Gallery.prototype.setup = function(){
		var self = this;
		this.navPre.addEvent('click', function(){
			if(self.photos.length < self.pageQuantity){
				return
			}
			var currentPage = self.pager.currentPage;
			var totalPages = Math.ceil(self.photos.length / self.pageQuantity);
			var nextPage = currentPage - 1;
			if(nextPage < 0){
				nextPage = totalPages - 1;
			}
			//console.log(currentPage, nextPage, totalPages);
			self.pager.update(totalPages, nextPage);
			var currentPhotos = self.photos.slice(currentPage*self.pageQuantity, (currentPage+1)*self.pageQuantity);
			var nextPhotos = self.photos.slice(nextPage*self.pageQuantity, (nextPage + 1)*self.pageQuantity);
			self.transition(false, currentPhotos, nextPhotos);
		});
		this.navNext.addEvent('click', function(){
			if(self.photos.length < self.pageQuantity){
				return
			}
			var currentPage = self.pager.currentPage;
			var totalPages = Math.ceil(self.photos.length / self.pageQuantity);
			var nextPage = currentPage + 1;
			if(nextPage >= totalPages){
				nextPage = 0;
			}
			//console.log(currentPage, nextPage, totalPages);
			self.pager.update(totalPages, nextPage);
			var currentPhotos = self.photos.slice(currentPage*self.pageQuantity, (currentPage+1)*self.pageQuantity);
			var nextPhotos = self.photos.slice(nextPage*self.pageQuantity, (nextPage + 1)*self.pageQuantity);
			self.transition(true, currentPhotos, nextPhotos);
		});
		this.pager.pages.addEvent('click:relay(.pager-page)', function(e, ele){
			if(ele.hasClass('active')){
				return
			}
			var active = self.pager.pages.getElement('.active');
			var currentPage = active.get('text') - 1;
			var nextPage = ele.get('text') - 1;
			var isNext = nextPage > currentPage;
			var currentPhotos = self.photos.slice(currentPage*self.pageQuantity, (currentPage+1)*self.pageQuantity);
			var nextPhotos = self.photos.slice(nextPage*self.pageQuantity, (nextPage + 1)*self.pageQuantity);
			self.transition(isNext, currentPhotos, nextPhotos);
			active.removeClass('active');
			ele.addClass('active');
			self.pager.currentPage = nextPage;
		});
	}
	Gallery.prototype.updateView = function(){
		var currentPage = this.pager.currentPage;
		var currentPhotos = this.photos.slice(currentPage*this.pageQuantity, (currentPage+1)*this.pageQuantity);
		var ele = this.$el;
		ele.empty();
		var htmlString = '<div class="room"><ul>';
		currentPhotos.forEach(function(photo){
			var selected = photo.isSelected ? 'selected' : '';
			htmlString += '<li photo_id="' + photo.photo_id + '" class="gallery-photo ' + selected + '"><img src="' + photo.filename + '"></li>';
		});
		htmlString += '</ul></div>';
		ele.appendHTML(htmlString);
		this.pager.update(Math.ceil(this.photos.length / this.pageQuantity));
		// update the time on the info board
		var timeString = currentPhotos[0]['timestamp'];
		var d = new Date(Number.from(timeString));
		timeString = d.toLocaleDateString() + " " + d.toLocaleTimeString();
		$('updateTime').set('text', timeString);
	}
	Gallery.prototype.setPageQuantity = function(number){
		this.pageQuantity = number;
		return this;
	}
	Gallery.prototype.setLoadQuantity = function(number){
		this.loadQuantity = number;
		return this;
	}
	Gallery.prototype.isBusy = function(){
		return this.processing;
	}
	Gallery.prototype.introduce = function(photolist){
		if(photolist && photolist.length > 0){
			this.rawData.append(photolist);
			if(!this.isBusy()){
				this.load();
			}
		}
	}
	Gallery.prototype.load = function(){
		var self = this;
		var imageSufix = self.imageSufix;
		if(this.rawData.length > 0){
			this.processing = true;
			this.operatingData = this.rawData.splice(0, this.loadQuantity);
			var feedback = [];
			this.operatingData.forEach(function(photo){
				var filename = photo.filename.replace(/(\.jpe?g)$/i, imageSufix + "$1");
				photo.filename = "/assets/" + photo.event_id + "/" + filename;
				var image = new Image();
				var sh = successhandle;
				var eh = errorHandle;

				image.onload = sh;
				image.onerror = eh;

				function successhandle(){
					feedback.push(true);
					photo.element = image;
					checkFeedback();
					unbind(image);
				}
				function errorHandle(){
					feedback.push(false);
					unbind(image);
				}

				function unbind(ele){
					ele.onload = null;
					ele.onerror = null;
				}

				function checkFeedback(){
					if(feedback.length === self.operatingData.length){
						self.operatingData.forEach(function(photo){
							if(typeOf(photo.element) === 'element'){
								self.photos.push(photo);
							}
						});
						self.operatingData = [];
						self.processing = false;
						self.updateView();
						self.load();
					}
				}
				image.setAttribute("src", photo.filename);
			});
		}

	}
	

})(window);